package com.simple.mipc.utils;

import android.os.IBinder;
import android.os.Messenger;

import com.simple.mipc.annotation.IPCProxy;
import com.simple.mipc.handler.MessageClient;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Objects;

public class ProxyUtil {

    /**
     * 通过接口，创建IPC通信的代理对象
     *
     * @param interfaceClass 接口类型
     * @param messenger      IPC通信对象
     * @param <T>            接口的泛型
     * @return IPC通信代理对象
     */
    public static <T> T proxyCreate(Class<?> interfaceClass, Messenger messenger, Messenger handler) {
        if (!interfaceClass.isInterface()) {
            throw new IllegalArgumentException(String.format("被代理的类：%s，必须是接口", interfaceClass));
        }
        ClassLoader classLoader = ProxyUtil.class.getClassLoader();
        Class<?>[] array = new Class[]{interfaceClass};
        return (T) Proxy.newProxyInstance(classLoader, array, new MessageClient(interfaceClass, messenger, handler));
    }

    /**
     * 扫描字段，并且注入字段，使用IBinder创建Messenger，同时返回Messenger
     *
     * @param instance 被扫描注入代理对象的实例
     * @param binder   远程链接的binder
     * @return messenger对象
     */
    public static Messenger initProxy(Object instance, IBinder binder, Messenger handler) {
        Field[] fields = ClassUtil.getFields(instance);
        Messenger messenger = new Messenger(binder);
        Arrays.stream(fields)
                .filter(field -> Objects.nonNull(field.getDeclaredAnnotation(IPCProxy.class)))
                .forEach(field -> {
                    Class<?> type = field.getType();
                    Object proxy = proxyCreate(type, messenger, handler);
                    FieldUtil.setValue(instance, field, proxy);
                });
        return messenger;
    }
}
